import { Component, OnInit } from '@angular/core';
import { NavController, ActionSheetController, PickerController } from '@ionic/angular';
import { NativeService } from 'src/app/providers/NativeService';
import * as constants from '../../../providers/Constants'
import { ToastService } from './../../../providers/toast/toast.service'
import { Storage } from 'src/app/providers/Storage';
import { Utils } from 'src/app/providers/Utils';
import { ActivatedRoute, Params } from '@angular/router';
import { LoanService } from 'src/app/services/loan.service';
import { AuthService } from 'src/app/services/auth.service';
import { OrderService } from 'src/app/services/order.service';

@Component({
  selector: 'app-info',
  templateUrl: './info.page.html',
  styleUrls: ['./info.page.scss'],
})
export class InfoPage implements OnInit {
  photo: string = '../../../../assets/img/me/touxiang.png';
  defaultColumnOptions = [
    [
      'woman',
      'Female',
      // 'Confidential',
      // '保密',
    ]
  ]
  sex: string = 'Edit';
  userNickName: string = 'Edit';
  userPhone: string = '';
  userAccount: string = '';
  thirdLogin: boolean = true;
  statusType:string='0';
  constructor(private nav: NavController,
    private actionSheetController: ActionSheetController,
    private pickerController: PickerController,
    private service: LoanService,
    private order: OrderService,
    private auth: AuthService,
    private toast: ToastService,
    private nativeService: NativeService) { }

  ngOnInit() {
    this.userPhone = Storage.localStorage.get('userPhone')
    
    if (!Storage.localStorage.get('thirdLogin')) {
      
      this.thirdLogin = false;
    }else{
      this.statusType=Storage.localStorage.get('thirdLogin')
    }
    this.getUserInfo();
    console.log('PhotoViewer-------------------');

  }
  updataImg() {
    
    if (this.thirdLogin) {
      console.log("123")
      this.presentActionSheet();
    }
  }
  updataInfo() {
    if (this.thirdLogin) {
      this.nav.navigateForward('updata-info');
    }
  }

  userNickName1() {
    let user = Storage.localStorage.get('userInfo');
    return user.userNickName;
  }
  updataSex() {
    if (this.thirdLogin) {
      this.openPicker(1, 2, this.defaultColumnOptions, res => {
        console.log(JSON.parse(res));
        let r = JSON.parse(res);
        this.upData(r.value, r.text);

      });
    }

  }
  ionViewDidEnter() {

  }
  // userNickName1(){
  //   Storage.localStorage.get('');
  // }
  getUserInfo() {
    this.auth.getUserInfo().subscribe(res => {
     
      // 保存成功返沪上一页，否则弹出提示框
      console.log('facebook头像', res);
      if (res.retCode == '000000') {
        if (res.info) {
          if (res.info.sex == '1') {
            this.sex = 'Male'
          } else if (res.info.sex == '0') {
            this.sex = 'Female'
          } else {
            this.sex = 'Confidential'
          }
          this.userNickName = res.info.userNickName;
          if(this.statusType=='google'){
            this.userAccount = Storage.localStorage.get('GoogleEmail');
          }else{
            this.userAccount = res.info.userPhone;
          }
        
          // if (!this.thirdLogin) {
          //   this.userAccount ='';
          //   this.userNickName = res.info.nickName;
          //   let userInfo = Storage.localStorage.get('userInfo');
          //   userInfo.userNickName = res.info.nickName;
          //   Storage.localStorage.set('userInfo', userInfo);
          //   this.photo = Utils.formatUrl(res.info.avatarUrl);
          // }
         
          this.photo=  this.order.getImageUrl()+res.info.avatarUrl;
          console.log('userNickName', this.userNickName);
          console.log('头像地址', this.photo);
        }
      } else if (constants.errCode[res.retCode]) {
        if (constants.errCode[res.retCode] != '0') {
          this.toast.show(constants.errCode[res.retCode]);
        }
      } else if (res.retMsg) {
        this.toast.show(res.retMsg);
      } else {
        this.toast.show("exception service routine");
      }
    });
  }

  upData(type, text, upType: boolean = false) {
    let photo = '';
    if (photo == '../../../../assets/img/activity/touxiang.png') {
      photo = ''
    }
    let data = {};
    if (!upType) {
      data = {
        userPhone: this.userPhone,
        sex: type,//男1 女0
      }
    } else {
      data = {
        userPhone: this.userPhone,
        avatarUrl: type,
      }
    }
    this.service.modifyUserInfo(data).subscribe(res => {
      // 保存成功返沪上一页，否则弹出提示框
      if (res.retCode == '000000') {
        if (!upType) {
          this.sex = text
        }
        // this.getUserInfo();
      } else if (constants.errCode[res.retCode]) {
        if (constants.errCode[res.retCode] != '0') {
          this.toast.show(constants.errCode[res.retCode]);
        }
      } else if (res.retMsg) {
        this.toast.show(res.retMsg);
      } else {
        this.toast.show("exception service routine");
      }
    });
  }
  async openPicker(numColumns = 1, numOptions = 5, multiColumnOptions, callback) {
    const picker = await this.pickerController.create({
      columns: this.getColumns(numColumns, numOptions, multiColumnOptions),
      cssClass: 'picker-controller',
      buttons: [
        {
          // cssClass:'white',
          text: 'Cancel',
          role: 'cancel'
        },
        {
          text: 'Confirm',
          handler: value => {
            // console.log(`Got Value ${value}`);

            callback(JSON.stringify(value.data))
          }
        }
      ]
    });
    await picker.present();
  }
  getColumns(numColumns, numOptions, columnOptions) {
    let columns = [];
    for (let i = 0; i < numColumns; i++) {
      columns.push({
        // name: `col-${i}`,
        name: `data`,
        options: this.getColumnOptions(i, numOptions, columnOptions)
      });
    }
    return columns;
  }
  getColumnOptions(columnIndex, numOptions, columnOptions) {
    let options = [];
    for (let i = 0; i < numOptions; i++) {
      options.push({
        text: columnOptions[columnIndex][i % numOptions],
        value: i
      });
    }
    return options;
  }
  async presentActionSheet() {
    // {
    //   text: 'Take a photo',
    //   handler: () => {
    //     this.nativeService.openCamera(1).subscribe(res => {
    //       console.log('base64', res);
    //       this.photo = res;
    //       this.updataLoadFile(res);
    //     }, err => {
    //       console.log('base64失败了', err);
    //     })
    //   }
    // },
    const actionSheet = await this.actionSheetController.create({
      // header: '确定要退出登录吗',
      mode: 'ios',
      cssClass: 'exit-action-sheet',
      buttons: [ {
        text: 'From my album',
        handler: () => {
          this.nativeService.openCamera(2).subscribe(res => {
            console.log('base64', res);
            this.photo = res;
            this.updataLoadFile(res);
          }, err => {
            console.log('base64失败了', err);
          })
          // this.nativeService.getPictures();
        }
      }, {
        text: 'Cancel',
        role: 'cancel',
        handler: () => {
          console.log('Cancel clicked');
        }
      }]
    });
    await actionSheet.present();
  }
  updataLoadFile(dataURL) {
    this.service.uploadFile({
      fileBase64Str: dataURL,
      name: new Date().getTime(),
      extFix: 'jpg',
    }).subscribe(res => {
      // 保存成功返沪上一页，否则弹出提示框
      if (res.retCode == '000000') {
        console.log('上传成功');
        this.upData(res.fileUuid, '', true);
      } else if (constants.errCode[res.retCode]) {
        if (constants.errCode[res.retCode] != '0') {
          this.toast.show(constants.errCode[res.retCode]);
        }
      } else if (res.retMsg) {
        this.toast.show(res.retMsg);
      } else {
        this.toast.show("exception service routine");
      }
    });
  }
}
